import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shopping_cart/model/product_model.dart';
import 'package:shopping_cart/model/shppping_cart.dart';

class ProductListPage extends StatefulWidget {
  const ProductListPage({Key? key}) : super(key: key);

  @override
  State<ProductListPage> createState() => _ProductListPageState();
}

class _ProductListPageState extends State<ProductListPage> {
  ProductModel model = ProductModel.init();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('商品列表'),
        actions: [
          IconButton(
            icon: Icon(Icons.shopping_cart),
            onPressed: () {
              Navigator.of(context).pushNamed('/cart');
            },
          )
        ],
      ),
      body: ListView.builder(itemBuilder: (context, index) {
        bool isInCart = Provider.of<ShoppingCart>(context).cart.any(
              (element) => element == model.list[index],
            );
        return ListTile(
          leading: Image.network(
            'http://www.tangguoketang.com/img/banner01.7c3681ef.png',
            width: 100,
          ),
          title: Text('${model.list[index].name}'),
          trailing: isInCart
              ? Icon(Icons.check)
              : IconButton(
                  icon: Icon(Icons.add),
                  onPressed: () {
                    Provider.of<ShoppingCart>(context, listen: false)
                        .add(model.list[index]);
                  },
                ),
        );
      }),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Provider.of<ShoppingCart>(context, listen: false).removeAll();
        },
        child: Text('${Provider.of<ShoppingCart>(context).cart.length}'),
      ),
    );
  }
}
